package com.gzx.risk.core.utils;

import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang3.StringUtils;

public class AESUtils {
    private static final String ENCODE = System.getProperty("file.encoding");
	private static String CHARSET_NAME = "UTF-8";
	private static final String ALGORITHM_AES = "AES";
	private static final String UTF8_CHARSET = "UTF-8";
	private static final String KEY_ALGORITHM = "RSA";

	private static boolean isBase64Encoded(String input) {
		try {
			Base64.getDecoder().decode(input);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	private static String getKey(String... keys) {
		return "w23456789987456a";
	}

	public static String decrypt(String input, String... keys) {
		if (StringUtils.isBlank(input))
			return input;
		if (!isBase64Encoded(input))
			return input;
		byte[] decodedValue = Base64.getDecoder().decode(input);
		if (decodedValue.length % 16 != 0)
			return input;
		try {
			String key = getKey(keys);
			SecretKeySpec skey = new SecretKeySpec(key.getBytes(CHARSET_NAME), "AES");
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
			cipher.init(2, skey);
			byte[] inputBytes = Base64.getDecoder().decode(input);
			return new String(cipher.doFinal(inputBytes), CHARSET_NAME);
		} catch (Exception e) {
			e.printStackTrace();
			return input;
		}
	}

	/**
	 * base64编码AES加密后的字符串
	 *
	 * @param content 需要加密的字符串
	 * @param strKey  秘钥key
	 * @throws Exception
	 */
	public static String encryptBase64DecorateAES(String content, String strKey) throws Exception {
		byte[] encryptAesBytes = encrypt(content, strKey);
		return byte2hex(encryptAesBytes);
	}

	/**
	 * 加密
	 *
	 * @param content 需要加密的内容
	 * @param strKey  加密秘钥
	 * @return 加密后的比特流
	 * @throws Exception
	 */
	private static byte[] encrypt(String content, String strKey) throws Exception {
		try {
			SecretKeySpec key = new SecretKeySpec(strKey.getBytes(), ALGORITHM_AES); // NOSONAR
			Cipher cipher = Cipher.getInstance(ALGORITHM_AES);
			byte[] byteContent = content.getBytes(UTF8_CHARSET);
			cipher.init(Cipher.ENCRYPT_MODE, key);
			return cipher.doFinal(byteContent);
		} catch (Exception e) {
			throw new Exception("use AES algorithm encrypt error");
		}

	}

	private static byte[] hex2byte(final String str) {
		if (str == null) {
			return new byte[] {};
		}
		String newStr = str.trim();
		int len = newStr.length();
		if (len <= 0 || len % 2 != 0) {
			return new byte[] {};
		}
		byte[] b = new byte[len / 2];
		try {
			for (int i = 0; i < newStr.length(); i += 2) {
				b[i / 2] = (byte) Integer.decode("0x" + newStr.substring(i, i + 2)).intValue();
			}
			return b;
		} catch (Exception e) { // NOSONAR
			return new byte[] {};
		}
	}

	private static String byte2hex(byte[] b) {
		StringBuilder hs = new StringBuilder();
		for (byte bi : b) {
			String temp = Integer.toHexString(bi & 0XFF);
			if (temp.length() == 1) {
				hs.append("0");
			}
			hs.append(temp);
		}
		return hs.toString().toUpperCase();
	}

	/**
	 * 解密经过base64编码后的AES加密过的字符串
	 *
	 * @param content    待解密的经过base64编码后的AES加密过的字符串
	 * @param secretSeed 秘钥种子
	 * @return 原始内容
	 * @throws Exception
	 */
	public static String decryptBase64DecorateAES(String content, String secretSeed) throws Exception {
		byte[] decryptResult = decrypt(hex2byte(content), secretSeed);
		return new String(decryptResult); // NOSONAR
	}

	/**
	 * 解密
	 *
	 * @param content 待解密内容
	 * @param strKey  解密密钥
	 * @return 解密后的
	 * @throws Exception
	 */
	private static byte[] decrypt(byte[] content, String strKey) throws Exception {
		try {
			SecretKeySpec key = new SecretKeySpec(strKey.getBytes(), ALGORITHM_AES);// NOSONAR
			Cipher cipher = Cipher.getInstance(ALGORITHM_AES);
			cipher.init(Cipher.DECRYPT_MODE, key);
			return cipher.doFinal(content);
		} catch (Exception e) {
			throw new Exception("use AES algorithm decrypt error");
		}
	}

	public static String myencrypt(String input, String... keys) {
	    // 检查输入是否为空
	    if (StringUtils.isBlank(input)) {
	        return input;
	    }
	    
	    try {
	        // 获取密钥
	        String key = getKey(keys);
	        // 创建AES密钥规范，使用与解密相同的字符集
	        SecretKeySpec skey = new SecretKeySpec(key.getBytes(CHARSET_NAME), "AES");
	        // 初始化加密器，使用相同的模式：AES/ECB/PKCS5PADDING
	        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
	        cipher.init(Cipher.ENCRYPT_MODE, skey);
	        
	        // 执行加密并对结果进行Base64编码
	        byte[] encryptedBytes = cipher.doFinal(input.getBytes(CHARSET_NAME));
	        return Base64.getEncoder().encodeToString(encryptedBytes);
	        
	    } catch (Exception e) {
	        // 加密失败时打印异常并返回原始输入
	        e.printStackTrace();
	        return input;
	    }
	}

    /**
     * 百融api aes加密
     * @param content
     * @param pwdKey
     * @return
     * @throws Exception
     */
    public static String encryptBr(String content, String pwdKey) throws Exception {
        if (!StringUtils.isBlank(content) && !StringUtils.isBlank(pwdKey)) {
            try {
                KeyGenerator kgen = KeyGenerator.getInstance("AES");
                SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
                secureRandom.setSeed(pwdKey.getBytes(StandardCharsets.UTF_8));
                kgen.init(128, secureRandom);
                SecretKey secretKey = kgen.generateKey();
                byte[] enCodeFormat = secretKey.getEncoded();
                SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
                Cipher cipher = Cipher.getInstance("AES");
                byte[] byteContent = content.getBytes(ENCODE);
                cipher.init(1, key);
                byte[] result = cipher.doFinal(byteContent);
                return org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(result);
            } catch (Exception e) {
                throw new Exception("AESException:对参数进行AES加解密过程中异常", e);
            }
        } else {
            throw new IllegalArgumentException("参数不合法");
        }
    }
	
	public static void main(String[] args) throws Exception {
		 String phone1 = "54Cs5widmzEnBeBUxeYtuQ==";
		 System.out.println(decrypt(phone1));
		 String phone = "13910711372";
		 String phone2=myencrypt(phone,getKey());
		 System.out.println(phone2+"---->"+decrypt(phone2));
		 
		String save = encryptBase64DecorateAES(phone, getKey());

		System.out.println(save);
		System.out.println(decryptBase64DecorateAES(save, getKey()));
	}
}
